/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pb138.jprvyd.gui.model;

import cz.muni.fi.pb138.jprvyd.Invoice;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;
import javax.swing.table.AbstractTableModel;

/**
 *
 * @author Jan
 */
public class Main_TableModel extends AbstractTableModel {

    private static int COLUMN_COUNT = 4;
    private List<Invoice> invoices;
    
    public Main_TableModel(List<Invoice> invoices) {
        this.invoices = invoices;
    }

    @Override
    public int getRowCount() {
        return invoices.size();
    }

    @Override
    public int getColumnCount() {
        return COLUMN_COUNT;
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        Invoice invoice = invoices.get(rowIndex);
        switch (columnIndex) {
            case 0:
                return invoice.getNumber();
            case 1:
                return invoice.getContact().getFirstName() + " " + invoice.getContact().getSurname();
            case 2:
                DateFormat dateFormatter = new SimpleDateFormat("dd. MM. yyyy");
                return dateFormatter.format(invoice.getDate());
            case 3:
                return invoice.getPrice();
            default:
                throw new IllegalArgumentException("columnIndex");
        }
    }

    public void addInvoice(Invoice invoice) {
        invoices.add(invoice);
        int lastRow = getRowCount() - 1;
        fireTableRowsInserted(lastRow, lastRow);
    }

    public void editInvoice(Invoice invoice) {
        int index = invoices.indexOf(invoice);
        invoices.set(index, invoice);
        fireTableRowsUpdated(index, index);
    }

    public void deleteInvoice(int row) {
        invoices.remove(invoices.get(row));
        fireTableRowsDeleted(row, row);
    }

    @Override
    public String getColumnName(int columnIndex) {
        switch (columnIndex) {
            case 0:
                return "Invoice number";
            case 1:
                return "Contact";
            case 2:
                return "Date";
            case 3:
                return "Price";
            default:
                throw new IllegalArgumentException("columnIndex");
        }
    }

    @Override
    public Class<?> getColumnClass(int columnIndex) {
        switch (columnIndex) {
            case 0:
                return Long.class;
            case 1:
                return String.class;
            case 2:
                return String.class;
            case 3:
                return Integer.class;
            default:
                throw new IllegalArgumentException("columnIndex");
        }
    }

}
